<template>
  <div style="display: inline-block;">
    <el-button @click.native.prevent="exportFun()" :loading="sending"><slot>导出</slot></el-button>
  </div>
</template>

<script>
  import {host} from '@/api/util/fetch';
  import {parseTime} from '@/utils/datetime';
  export default {
    name: 'ExportFile', //导出文件
    props:{
      apiInfo:{
        type:Object,
        default: () => {
          return {
            url:'', //接口
            method:'get',
            data:null, //请求参数
          };
        },
      },
    },
    data()
    {
      return {
        sending:false,
      }
    },
    methods: {
      exportFun()
      {
        if(this.sending)
        {
          return;
        }

        let _this = this;
        _this.sending = true;

        let url = host + this.apiInfo.url;
        let method = this.apiInfo.method;
        let data = this.apiInfo.data;
        let token = this.$store.getters.token;


        let xhr = new XMLHttpRequest();
        xhr.timeout = 10000;
        xhr.responseType = "blob";    // 返回类型blob
        xhr.open(method, url, true);
        xhr.setRequestHeader('token',token);
        //请求完成
        xhr.onload = function () {
          if (this.status === 200) {
            _this.downFile(this.response);
          }
          else
          {
            _this.$message({
              message: '出错了，请稍后重试!',
              showClose: true,
              type: 'error',
              duration: 4000
            });
          }
          setTimeout(()=> {
            _this.sending = false;
          },2000);
        };
        xhr.onerror = function () {
          _this.$message({
            message: '出错了，请稍后重试!',
            showClose: true,
            type: 'error',
            duration: 4000
          });

          setTimeout(()=> {
            _this.sending = false;
          },2000);
        };
        // 发送ajax请求
        xhr.send(data);

      },
      downFile(blob)
      {
        //console.log(blob);
        if(blob.type==='text/xml')
        {
          this.$message({
            message: '出错了，请重新登录!',
            showClose: true,
            type: 'error',
            duration: 4000
          });
          return;
        }
        else if(blob.type==='application/json')
        {
          this.$message({
            message: '出错了，下载链接不存在!',
            showClose: true,
            type: 'error',
            duration: 4000
          });
          return;
        }

        let fileName = 'File_' + parseTime(new Date(),"{y}{m}{d}{h}{i}{s}");

        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        }
        else
        {
          let downloadUrl = window.URL.createObjectURL(blob);
          let anchor = document.createElement("a");
          anchor.href = downloadUrl;
          anchor.download = fileName;

          //firefox bugfix
          document.body.appendChild(anchor);

          let evt = document.createEvent("HTMLEvents");
          evt.initEvent("click", false, false);
          anchor.dispatchEvent(evt);

          anchor.click();
          window.URL.revokeObjectURL(blob);

          document.body.lastChild.remove();
        }
      }
    }
  }
</script>

<style lang="less" scoped>

</style>